<template>
  <div class="app-container">
    <FilterSearch class="filter-search" :value="queryParams" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }"
      :config="configData" labelWidth="110px" position="right"></FilterSearch>
    <div class="main">
      <div class="table">
        <el-table stripe @selection-change="tableChange" :data="tableData.rows" border v-loading="tableData.loading"
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="id" width="60">
          </el-table-column>
          <el-table-column prop="algorName" label="算法模型名称" width="120">
          </el-table-column>
          <el-table-column prop="funContent" label="函数内容" min-width="450">
            <template v-slot="scope">
              <el-popover placement="top-start" :width="500" trigger="hover">
                <div style="max-height: 150px;">
                  <el-scrollbar :height="150">
                    {{ scope.row.funContent }}
                  </el-scrollbar>
                </div>
                <template #reference>
                  <div class="ellipsis_3">
                    {{ scope.row.funContent }}
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="genNum" label="可视化数据条数" width="120">
          </el-table-column>
          <el-table-column prop="uid" label="创建者" width="100">
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.createdTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="修改时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.updateTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="140">
            <template v-slot="scope">
              <el-button @click="handleClick(scope.row, 'update')" type="text" size="small">编辑</el-button>
              <el-button @click="handleClick(scope.row, 'copy')" type="text" size="small">复制</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination @current-change="currentChange" layout="total, prev, pager, next, jumper" :total="tableData.total"
          :current-page="queryParams.currentPage" :page-size="queryParams.size">
        </el-pagination>
      </div>
    </div>
    <el-dialog v-model="rowData.diaVis" :title="rowData.formTit" :close-on-click-modal="false" :show-close="false"
      width="900px">
      <div class="box-container">
        <div class="con-left">
          <el-form label-position="left" :model="rowData.formInline" ref="formState" label-width="160px" :rules="rules">
            <el-form-item label="算法模型名称:" prop="algorName">
              <el-input @change="algorNameRules" v-model="rowData.formInline.algorName" placeholder="请输入算法模型名称" />
            </el-form-item>
            <el-form-item label="可视化数据条数:" prop="genNum">
              <el-input v-model="rowData.formInline.genNum" placeholder="请输入可视化数据条数"
                @input="rowData.formInline.genNum = rowData.formInline.genNum.replace(/-/g, '').replace(/[^0-9]/g, '')" />
            </el-form-item>
            <el-form-item label="请选择可视化数据:">
              <div class="col">
                <div class="btn2" @click="handleClick({}, 'diaVis2')">
                  <el-icon>
                    <Setting />
                  </el-icon>
                </div>
              </div>
            </el-form-item>
            <el-form-item class="margin-bottom" label="可视化数据字段配置:">
              <el-scrollbar style="height:290px;">
                <ul class="list">
                  <li v-for="(item, index) in rowData.formInline.visualOriginalFieldConfigs" :key="index">
                    <div class="left">
                      <el-popover placement="top-start" :width="200" trigger="hover">
                        {{ item.visualFieldName || item.fieldName }}
                        <template #reference>
                          <div class="ellipsis_1">
                            {{ item.visualFieldName || item.fieldName }}
                          </div>
                        </template>
                      </el-popover>
                    </div>
                    <div class="right">
                      <div class="icon" @click="listChange(item, index, 0)">
                        <img src="../../assets/images/icon001.png" alt="">
                      </div>
                      <div class="icon" @click="listChange(item, index, 1)">
                        <el-icon :size="16">
                          <Delete />
                        </el-icon>
                      </div>
                    </div>
                  </li>
                  <li v-if="rowData.formInline.visualOriginalFieldConfigs.length == 0" class="tip">
                    暂无数据~</li>
                </ul>
              </el-scrollbar>
            </el-form-item>
          </el-form>
        </div>
        <div class="con-right">
          <div class="title">
            <div class="tit">
              算法模型字段配置
            </div>
            <div class="btns">
              <div class="btn" @click="rowData.formInline.funContent = ''">
                清空
              </div>
            </div>
          </div>
          <el-input placeholder="请输入数据字段函数配置" v-model="rowData.formInline.funContent" resize="none" :rows="18"
            type="textarea" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(0)">取消</el-button>
          <el-button type="primary" @click="submit(0)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="rowData.diaVis2" width="60%">
      <div>
        <VisualTable ref="visualTable"></VisualTable>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(1)">取消</el-button>
          <el-button type="primary" @click="submit(1)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed, onBeforeMount, onBeforeUnmount } from "vue"
import {
  getList, getColumns, insertAlgor, selectOne, selectByIds, updateAlgor,
  delateAlgor, insertRules
} from "@/api/algorModel.js"
import { formatDate } from "../../utils/index.js"
import VisualTable from "@/components/VisualTable/index.vue"
import { formData } from "@/utils/validate.js"
export default {
  components: {
    VisualTable
  },
  setup() {
    const { proxy } = getCurrentInstance();

    const tableData = reactive({
      rows: [
      ],
      total: 0,
      loading: false,
      selection: []
    });
    const queryParams = ref({
      currentPage: 1,
      size: 10,
      algorName: ""
    });
    const timeOut = {
      setTime1: null,
      setTime2: null,
      setTime3: null,
      setTime4: null,
      setTime5: null,
      setTime6: null,
    }
    const configData = computed(() => {
      let config = {
        itemConfig: [
          {
            type: "input",
            prop: "algorName",
            clearable: "关闭",
            label: "算法模型名称",
            placeholder: "请输入",
          }
        ],
        operate: [
          {
            icon: "Search",
            type: "primary",
            name: "查询",
            handleClick: getLoad,
            rule: true,
          },
          {
            icon: "RefreshLeft",
            type: "primary",
            name: "重置",
            handleClick: reset,
            rule: true,
          },
          {
            icon: "Plus",
            type: "primary",
            name: "新增",
            handleClick: insert,
            rule: true,
          },
          {
            icon: "Delete",
            type: "primary",
            name: "批量删除",
            handleClick: allDel,
            rule: true,
          }
        ],
        rules: {},
      };
      return config;
    })

    const validateAlgorName = (rule, value, callback) => {
      if (proxy.rowData.taskNameStatus) {
        callback(new Error("算法模型名称已重复,请修改"));
      } else {
        callback();
      }
    };
    const rules = computed(() => {
      let rules = {
        algorName: [
          { required: true, trigger: "blur", message: "请输入算法模型名称" },
          { required: true, trigger: "change", message: "请输入算法模型名称" },
          {
            validator: validateAlgorName,
            trigger: "change",
          },
          {
            validator: validateAlgorName,
            trigger: "blur",
          },
        ],
        genNum: [
          { required: true, trigger: "blur", message: "请输入可视化数据条数" },
          { required: true, trigger: "change", message: "请输入可视化数据条数" },
        ]
      }
      return rules;
    })
    const rowData = reactive({
      diaVis: false,
      diaVis2: false,
      formInline: {
        visualDataFieldConfigs: [],
        visualOriginalFieldConfigs: [],
        funContent:`function validate(data){
            var result = {
              code: //1:失败，0:成功,
              msg: //错误信息
            }
            return JSON.stringify(result);
        }`
      },
      formTit: "新增算法模型",
      index: -1,
      status: 0,
      algorNameStatus: false
    })
    const getDate = (date) => {
      return formatDate(date)
    }
    const currentChange = (currentPage) => {
      proxy.queryParams.currentPage = currentPage;
      getLoad();
    }
    const tableChange = (selection) => {
      proxy.tableData.selection = selection;
    }
    const listChange = (row, ind, type) => {
      switch (type) {
        case 0:
          proxy.rowData.formInline.visualOriginalFieldConfigs.splice(ind, 1);
          proxy.rowData.formInline.visualOriginalFieldConfigs.unshift(row);
          break;
        case 1:
          proxy.rowData.formInline.visualOriginalFieldConfigs.splice(ind, 1);
          break;
        default:
          break;
      }
    }
    const getLoad = () => {
      proxy.tableData.loading = true;
      getList(proxy.queryParams).then(res => {
        proxy.tableData.loading = false;
        if (res.status == 'success') {
          ElMessage.success('查询成功');
        } else {
          ElMessage.error('查询失败');
          return;
        }
        proxy.tableData.rows = res.data.records;
        proxy.tableData.total = res.data.total;

      })
    }
    const insert = () => {
      proxy.rowData.diaVis = true;
      proxy.rowData.formTit = "新增算法模型";
      proxy.rowData.status = 0;
      proxy.rowData.formInline = {
        visualDataFieldConfigs: [],
        visualOriginalFieldConfigs: [],
        funContent:`function validate(data){
        var result = {
          code: //1:失败，0:成功,
          msg: //错误信息
        }
        return JSON.stringify(result);
}`
      };
      proxy.rowData.index = -1;
    }
    const algorNameRules = () => {
      insertRules(proxy.rowData.formInline.algorName).then(res => {
        if (res.data) {
          proxy.rowData.algorNameStatus = true;
        } else {
          proxy.rowData.algorNameStatus = false;
        }
        timeOut.setTime1 = setTimeout(() => {
          proxy.$refs.formState.validateField("algorName");
        }, 100);
      })
    }
    const handleClick = (row, type) => {
      switch (type) {
        case 'update':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.formInline.visualOriginalFieldConfigs = res.data.algorVisualFieldConfigs;
            proxy.rowData.formTit = "编辑算法模型";
            proxy.rowData.status = 1;
            proxy.rowData.diaVis = true;
            proxy.rowData.index = -1;
          })
          break;
        case 'diaVis2':
          proxy.rowData.diaVis2 = true;
          timeOut.setTime2 = setTimeout(() => {
            if (proxy.rowData.status == 1 || proxy.rowData.formInline.visualIds) {
              selectByIds(proxy.rowData.formInline.visualIds).then(res => {
                proxy.$refs.visualTable.changeData.rows = res.data;
                setTimeout(() => {
                  proxy.$refs.visualTable.checkStatus();
                }, 50);
              })
            }
          }, 100);
          break;
        case 'copy':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.formInline.id = null;
            proxy.rowData.formInline.algorName = "";
            proxy.rowData.formInline.visualOriginalFieldConfigs = res.data.algorVisualFieldConfigs;
            proxy.rowData.formTit = "复制算法模型";
            proxy.rowData.status = 0;
            proxy.rowData.diaVis = true;
            proxy.rowData.index = -1;
          })
          break;
        default:
          break;
      }
    }
    const cancel = (type) => {
      switch (type) {
        case 0:
          proxy.rowData.formInline = {
            visualDataFieldConfigs: [],
            visualOriginalFieldConfigs: [],
            funContent:`function validate(data){
        var result = {
          code: //1:失败，0:成功,
          msg: //错误信息
        }
        return JSON.stringify(result);
}`
          };
          timeOut.setTime3 = setTimeout(() => {
            proxy.$refs.formState.clearValidate();
            proxy.rowData.formTit = "新增可视化数据";
            proxy.rowData.diaVis = false;
            proxy.rowData.diaVis2 = false;
            proxy.rowData.status = 0;
            proxy.rowData.index = -1;
          }, 100);
          break;
        case 1:
          proxy.$refs.visualTable.cancel();
          timeOut.setTime4 = setTimeout(() => {
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
        default:
          proxy.rowData.formInline = {
            visualDataFieldConfigs: [],
            visualOriginalFieldConfigs: [],
            funContent:`function validate(data){
        var result = {
          code: //1:失败，0:成功,
          msg: //错误信息
        }
        return JSON.stringify(result);
}`
          };
          timeOut.setTime5 = setTimeout(() => {
            proxy.$refs.formState.clearValidate();
            proxy.rowData.diaVis = false;
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
      }
    }
    const submit = (type) => {
      switch (type) {
        case 0:
          proxy.$refs.formState.validate(valid => {
            if (valid) {
              let VisualDataList = proxy.rowData.formInline.visualOriginalFieldConfigs;
              if (proxy.rowData.formInline.visualOriginalFieldConfigs.length <= 0) {
                ElMessage.info("请选择可视化数据字段");
                return;
              }
              let algorVisualFieldConfigs = [];
              for (const key in VisualDataList) {
                let param = {
                  visualId: VisualDataList[key].id,
                  fieldName: VisualDataList[key].visualFieldName || VisualDataList[key].fieldName,
                  fieldIndex: key,
                }
                algorVisualFieldConfigs.push(param);
              }
              let params = JSON.stringify({
                algorName: proxy.rowData.formInline.algorName,
                funContent: proxy.rowData.formInline.funContent,
                algorVisualFieldConfigs,
                visualIds: proxy.rowData.formInline.visualIds,
                genNum: proxy.rowData.formInline.genNum
              });
              if (proxy.rowData.status == 0) {
                insertAlgor(params).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel(0);
                    getLoad();
                  } else {
                    ElMessage.error(res.msg);
                    return;
                  }
                  proxy.rowData.diaVis = false;
                })
              } else {
                algorVisualFieldConfigs = algorVisualFieldConfigs.map(item => {
                  item.algorId = proxy.rowData.formInline.id;
                  return item
                })
                let params = JSON.stringify({
                  id: proxy.rowData.formInline.id,
                  algorName: proxy.rowData.formInline.algorName,
                  funContent: proxy.rowData.formInline.funContent,
                  algorVisualFieldConfigs,
                  visualIds: proxy.rowData.formInline.visualIds,
                  genNum: proxy.rowData.formInline.genNum
                });
                updateAlgor(params).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel(0);
                    getLoad();
                  } else {
                    ElMessage.error(res.msg);
                    return;
                  }
                  proxy.rowData.diaVis = false;
                })
              }
            }
          })
          break;
        case 1:
          let param = proxy.$refs.visualTable.changeData.rows;
          let ids = "";
          let list = param.map(it => {
            ids += it.id + ',';
            return it.id;
          })
          ids = ids.slice(0, ids.length - 1);
          proxy.rowData.formInline.visualIds = ids;

          getColumns(list).then(res => {
            console.log(res.data);
            proxy.rowData.formInline.visualOriginalFieldConfigs = res.data;
          })

          proxy.$refs.visualTable.cancel();
          timeOut.setTime6 = setTimeout(() => {
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
        default:
          break;
      }
    }
    const reset = () => {
      proxy.rowData.diaVis = false;
      proxy.rowData.diaVis2 = false;
      proxy.rowData.formInline = {
        visualDataFieldConfigs: [],
        visualOriginalFieldConfigs: [],
        funContent:`function validate(data){
        var result = {
          code: //1:失败，0:成功,
          msg: //错误信息
        }
        return JSON.stringify(result);
}`
      };
      proxy.rowData.formTit = "新增可视化数据";
      proxy.rowData.index = -1;
      proxy.rowData.status = 0;
      proxy.queryParams = {
        currentPage: 1,
        size: 10,
        algorName: ""
      };
      getLoad();
    }
    const allDel = () => {
      if (proxy.tableData.selection.length <= 0) {
        ElMessage.info('请选择数据');
        return;
      }
      let ids = proxy.tableData.selection.map(it => {
        return it.id;
      })
      delateAlgor(formData({ ids })).then(res => {
        if (res.status == 'success') {
          ElMessage.success(res.msg);
          getLoad();
        } else {
          ElMessage.error('删除失败');
          return;
        }
      })
    }

    onBeforeMount(() => {
      getLoad();
    })
    onBeforeUnmount(() => {
      for (const key in timeOut) {
        if (timeOut[key]) {
          clearTimeout(timeOut[key]);
        }
      }
    })

    return {
      queryParams, configData, rowData, rules, tableData,
      currentChange, tableChange, getDate, submit, cancel, listChange,
      handleClick, algorNameRules
    }
  }
}


</script>
<style lang="scss" scoped>
$border-color: #c1c5cd;

.main {
  .page {
    padding: 10px 0;
    float: right;
  }
}

.box-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .con-left {
    width: 48%;

    .el-select {
      width: 100%;
    }

    .col {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: flex-start;

      .btn {
        min-width: 100px;
        width: 100px;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        margin-left: 10px;
        border-radius: 5px;
        border: solid 1px $border-color;
        padding: 0 5px;

        .txt {
          font-size: 12px;
        }

        &:hover {
          cursor: pointer;
        }
      }

      .btn2 {
        min-width: 50px;
        width: 50px;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        border-radius: 5px;
        border: solid 1px $border-color;
        padding: 0 5px;
        height: 32px;

        .txt {
          font-size: 12px;
        }

        &:hover {
          cursor: pointer;
        }
      }
    }

    .el-scrollbar {
      width: 100%;
      border: solid 1px #dcdfe6;
      border-radius: 4px;
    }

    .margin-bottom {
      margin-bottom: 0px;
    }

    .list {
      padding: 0;
      margin: 0;
      list-style-type: none;
      border-radius: 4px;

      li {
        &:last-child {
          border-bottom: none;
        }

        border-bottom: solid 1px #dcdfe6;
        padding: 0 10px;
        font-size: 12px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        &.sel {
          background-color: #f2f2f2;
        }

        &.tip {
          text-align: center;
          display: block;
          font-size: 12px;
          color: #999999;
        }

        .left {
          width: calc(100% - 60px);
        }

        .right {
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;

          .icon {
            width: 20px;
            position: relative;
            margin-right: 10px;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;

            &:hover {
              cursor: pointer;
            }

            img {
              width: 100%;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
        }

        .checkbox {
          border: solid 1px #dcdfe6;
          border-radius: 2px;
          width: 14px;
          height: 14px;

          &:hover {
            border-color: #409eff;
            cursor: pointer;
          }

          position: relative;

          .el-icon {
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            position: absolute;
          }

          &.check {
            border: solid 1px #409eff;
            background-color: #409eff;

            .el-icon {
              color: #ffffff;
            }
          }
        }
      }
    }
  }

  .con-right {
    width: 48%;

    .title {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .tit {
        font-size: 16px;
        font-weight: 700;
      }

      .btns {
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        align-items: center;

        .btn {
          padding: 5px 10px;
          border-radius: 5px;
          border: solid 1px #eeeeee;
          margin-left: 10px;

          &:hover {
            cursor: pointer;
          }
        }
      }
    }
  }
}

.ellipsis_3 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.ellipsis_1 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

::v-deep .el-form-item__label {
  font-weight: 700;
}
</style>